﻿using PressureTest.Main.Device;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PressureTest
{
    public partial class DeviceManageForm : Form
    {

        /// <summary>模型
        /// 
        /// </summary>
        private Device obj = new Device();

        /// <summary>重复检测
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckNameRepeat()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["name"] = DeviceNameTextBox.Text;
            List<Device> list = SqlSugarHelper.Inquireable<Device>(where);
            int count = list.Count;
            if (count > 0)
            {
                Alert.Error(where["name"] + "设备已存在");
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>检查端口是否重复
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckPortRepeat() 
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["port"] = PortAddressComboBox.Text;
            List<Device> list = SqlSugarHelper.Inquireable<Device>(where);
            int count = list.Count;
            if (count > 0)
            {
                Alert.Error(where["port"] + "不能重复绑定设备");
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>刷新界面
        /// 
        /// </summary>
        private void FreshForm()
        {
            DeviceNumberTextBox.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            DeviceAddressTextBox.Text = "";
            DeviceNameTextBox.Text = "";
            PortAddressComboBox.SelectedIndex = -1;
            BaudRateComboBox.SelectedIndex = -1;
            obj = new Device();
        }

        /// <summary>操作成功
        /// 
        /// </summary>
        private void OperationSuccess()
        {
            Task.Run(() =>
            {
                LoadDevicePointList();
            });
            FreshForm();
        }

        /// <summary>设备点位列表
        /// 
        /// </summary>
        public void LoadDevicePointList()
        {
            List<Device> list = SqlSugarHelper.Inquireable<Device>(null);
            UpdateDataGridViewRow(list);
            this.HideWaitForm();
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateDataGridViewRow(List<Device> list)
        {
            if (DataGridView1.Rows.Count > 1)
            {
                this.Invoke(new Action(() =>
                {
                    DataGridView1.Rows.Clear();
                }));
            }

            foreach (Device item in list)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(dataGridViewBoxCell(item.number.ToString()));
                row.Cells.Add(dataGridViewBoxCell(item.name));
                row.Cells.Add(dataGridViewBoxCell(item.address.ToString()));
                row.Cells.Add(dataGridViewBoxCell(item.port));
                row.Cells.Add(dataGridViewBoxCell(item.baudRate.ToString()));
                row.Height = 40;
                this.Invoke(new Action(() =>
                {
                    DataGridView1.Rows.Add(row);
                }));

            }
        }

        // <summary> 创建DataGridViewTextBoxCell
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private DataGridViewTextBoxCell dataGridViewBoxCell(string str)
        {
            DataGridViewTextBoxCell cell1 = new DataGridViewTextBoxCell();
            cell1.Value = str;
            return cell1;
        }

        public DeviceManageForm()
        {
            InitializeComponent();
        }

        /// <summary>确定
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            if (DeviceNameTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入设备名称");
                DeviceNameTextBox.Focus();
                return;
            }

            if (DeviceAddressTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入设备地址");
                DeviceAddressTextBox.Focus();
                return;
            }

            if (PortAddressComboBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请选择串口地址");
                return;
            }

            if (BaudRateComboBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请选择波特率");
                return;
            }

            if (obj.number > 0)
            {
                if (obj.name != DeviceNameTextBox.Text)
                {
                    bool repeatRes = CheckNameRepeat();
                    if (repeatRes)
                    {
                        return;
                    }
                }
                obj.number = DeviceNumberTextBox.Text.ToInt();
                obj.name = DeviceNameTextBox.Text;
                obj.address = DeviceAddressTextBox.Text.ToInt();
                obj.port = PortAddressComboBox.Text;
                obj.baudRate = BaudRateComboBox.Text.ToInt();
                List<Device> list = new List<Device>();
                list.Add(obj);
                int res = SqlSugarHelper.Updateable<Device>(list);
                if (res > 0)
                {
                    
                    OperationSuccess();
                }
                else
                {
                    Alert.Error("编辑设备失败");
                }

            }
            else
            {
                bool repeatRes = CheckNameRepeat();
                if (repeatRes)
                {
                    return;
                }

                obj.number = DeviceNumberTextBox.Text.ToInt();
                obj.name = DeviceNameTextBox.Text;
                obj.address = DeviceAddressTextBox.Text.ToInt();
                obj.port = PortAddressComboBox.Text;
                obj.baudRate = BaudRateComboBox.Text.ToInt();
                List<Device> list = new List<Device>();
                list.Add(obj);
                int res = SqlSugarHelper.Insertable(list);
                if (res > 0)
                {
                    OperationSuccess();
                }
                else
                {
                    Alert.Error("添加设备失败");
                }
            }
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            OperationSuccess();
        }

        private void DeviceManageForm_Load(object sender, EventArgs e)
        {
            this.ShowWaitForm("加载设备");
            OperationSuccess();
        }

        /// <summary>点位
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PointManageMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }

            DevicePointForm frm = new DevicePointForm();
            frm.DeviceName = obj.name;
            frm.DeviceNumber = obj.number.ToString();
            frm.DeviceAddress = obj.address;
            frm.Text = obj.name + "点位管理";
            frm.ShowDialog();
        }

        /// <summary>编辑
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }
            DeviceNumberTextBox.Text = obj.number.ToString();
            DeviceNameTextBox.Text = obj.name;
            DeviceAddressTextBox.Text = obj.address.ToString();
            PortAddressComboBox.SelectedItem = obj.port;
            BaudRateComboBox.SelectedItem = obj.baudRate.ToString();
        }

        /// <summary>删除
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }
            res = this.ShowAskDialog2("友情提示", "您确定要删除吗?", true);
            if (res)
            {
              
                List<Device> list = new List<Device>();
                list.Add(obj);
                int deleteRes = SqlSugarHelper.Deleteable(list);
                if (deleteRes > 0)
                {
                    OperationSuccess();
                }
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist()
        {
            int number = SelectedRowPrimaryKey();
            obj = DeviceWithNumber(number);
            if (obj == null)
            {
                this.ShowErrorDialog2("记录不存在");
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>选中记录主键值
        /// 
        /// </summary>
        /// <returns></returns>
        private int SelectedRowPrimaryKey()
        {
            int index = this.DataGridView1.CurrentRow.Index;
            return this.DataGridView1.Rows[index].Cells[0].Value.ToString().ToInt();
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private Device DeviceWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["number"] = number;
            List<Device> list = SqlSugarHelper.Inquireable<Device>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>双击某条记录
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView1.ClearSelection();
            DataGridView1.Rows[e.RowIndex].Selected = true;
            DataGridView1.CurrentCell = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            OperationMenu.Show(MousePosition.X, MousePosition.Y);
        }
    }
}
